package com.itheima.listener;


import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;


/**
 * @Author: taku
 * @CreateTime: 2020-04-27 17:53
 * @Description: 监听器
 */
@Component
public class Mylistener {

    @RabbitListener(queues = "dirQueue_spring")
    public void shoeMessage(Message message, Channel channel, String msg) {
        // System.out.println(new Date() + "消息已查收,内容是:");
        // System.out.println(msg);
         long tag = message.getMessageProperties().getDeliveryTag();
        // System.out.println("deliveryTag: " + tag );
        // System.out.println();
        // 接收处理
        try {
            // DeliveryTag 每次+1 ,可以作为消息处理通道的名字(单条消息对应的通道)
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//            int i= 1 / 0;
             System.out.println(new Date() + "消息已查收,内容是:");
             System.out.println(msg);
             channel.basicAck(tag,false);
//             Thread.sleep(1000);
        } catch (Exception e) {

            try {
                e.printStackTrace();
                // (deliveryTag, multiple, requeue
//                channel.basicNack(tag,false,true);
//                channel.basicReject(tag,false) 是否批量处理,是否拒绝后返回队列
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    // 死信队列直接拒收传入死信交换机
    @RabbitListener(queues = "deal_queue")
    public void dealLetter(Message message, Channel channel, String msg) {
        try {
            System.out.println("直接拒收来自死信队列的信息");
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    // 延时效果实现
    @RabbitListener(queues = "live_queue")
    public void delay(Message message, Channel channel, String msg) {
        try {
            msg = msg + "到达时间" + new Date();
            System.out.println(msg);
            System.out.println("确认已付款,开始安排发货");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
